       //google analytics
         var _gaq = _gaq || [];
         _gaq.push(['_setAccount', 'UA-12520737-7']);
         _gaq.push(['_trackPageview']);
		 
		 var _latestAppdemo = "";


        // Display tip when app setting is null
        if(location.search == "?is_first=1"){
           document.getElementById("fresh_man_tip").style.display="block"; 
        }



        // handler
        document.getElementById('delete_history_trigger').onclick=delete_history;
        document.getElementById('save_button').onclick=save_options;
        document.getElementById('save_as_button').onclick=save_as_options;
        document.getElementById('reset_button').onclick=reset_options;


        var nodeDefault = {
            "app_height":localStorage['app_height']||700, 
            "app_url":localStorage['app_url']||"http://static.gip.happyelements.com/client/1.0.0/appdemo_9.75450.swf", 
            "app_config":localStorage['app_config']||""
        };
        if(localStorage['app_height']){
            delete localStorage['app_height'];
            delete localStorage['app_url'];
            delete localStorage['app_config'];
        }

        // record current swap type wrapper id
        var SWAP_TYPE_WRAPPER_ID;

        init();


        function init(){
            render_history();
            restore_options();
            change_config();
            change_swap_type();
			check_latest_appdemo();
        }
		
		function check_latest_appdemo(){
			var xhr = new XMLHttpRequest();
			xhr.open("GET", "http://gip-portal.happyelements.net/?method=GetAppXml&keyName=gameSwfUrl", true);
			xhr.onreadystatechange = function() {
			  if (xhr.readyState == 4) {
			    // WARNING! Might be injecting a malicious script!
			    var data = JSON.parse(xhr.responseText);
				if(data && data["gameSwfUrl"]){
					_latestAppdemo = data["gameSwfUrl"];
					if(parse_appdemo_version(_latestAppdemo) != parse_appdemo_version($("#app_url").val())){
						add_get_appdemo_button(parse_appdemo_version(_latestAppdemo));
					}
				}    
			  }
			}
			xhr.send();
		}
		
		function parse_appdemo_version(url){
			//http://static.gip.happyelements.com/client/1.0.0/appdemo_9.75450.swf
			url = url || "";
			var start = url.indexOf("appdemo");
			var end = url.indexOf(".swf");
			return url.slice(start, end);
		}
		
		function add_get_appdemo_button(version){
			var b = $("<b />").css("color", "red").text("Honey,Honey! A new " + version + " has been available!");
			//<input type="button" value="get the latest Appdemo" onClick="change_latest_appdemo(this)" />
			var btn = $("<input />").attr({type:"button", value:"GET!"}).click(change_latest_appdemo);
			$("#option_get_latest").append(b, btn);
		}
		
		function change_latest_appdemo(){
			$("#app_url").val(_latestAppdemo);
			$("#option_get_latest input").remove();
			$("#option_get_latest b").remove();
		}

        // Saves options to localStorage.
        function save_options() {
            var appData = {};
            for (var x in nodeDefault) {
                var nodeId = x;
                appData[nodeId]=document.getElementById(nodeId).value;
            }
            var historyNode = document.getElementById("my_history");
            var historyName = historyNode.options[historyNode.selectedIndex].value;

            var oldHistoryData = {"Default":nodeDefault};
            if(localStorage["history"] !== undefined){
                oldHistoryData = JSON.parse(localStorage["history"]);
            }

            appData['swap_type'] = SWAP_TYPE_WRAPPER_ID;
            appData['gip_app_id'] = document.getElementById("gip_app_id").value;
            appData['frame_url'] = document.getElementById("frame_url").value;

            oldHistoryData[historyName] = appData;
            localStorage["history"] = JSON.stringify(oldHistoryData);

            localStorage["config_name"] = historyName;

            // Update status to let user know options were saved.
            show_tip("&nbsp;&nbsp;&nbsp;Options Saved.&nbsp;&nbsp;");
            setTimeout(function() {
               // window.close();
            }, 1000);

            _gaq.push(['_trackEvent', 'option_save', 'clicked']);
        }

        // Saves current options as a new config.
        function save_as_options(){
            var historyName = prompt("Please input history name used to identify your current config:");
            if(historyName == null){
                return false;
            }
            if(historyName === ""){
                alert("History name can't be empty!");
                return false;
            }

            var oldHistoryData = {"Default":nodeDefault};
            if(localStorage["history"] !== undefined){
                oldHistoryData = JSON.parse(localStorage["history"]);
            }
            if(oldHistoryData[historyName] !== undefined){
                if(!confirm("There has been a config named " + historyName + ".\n Are your sure to override it with your current config?")){
                    return false;
                } 
            }

            var historyItem = {};
            for (var x in nodeDefault) {
                var nodeId = x;
                historyItem[nodeId]=document.getElementById(nodeId).value;
            }

            historyItem['swap_type'] = SWAP_TYPE_WRAPPER_ID;
            historyItem['gip_app_id'] = document.getElementById("gip_app_id").value;
            historyItem['frame_url'] = document.getElementById("frame_url").value;

            oldHistoryData[historyName] = historyItem;

            localStorage["config_name"] = historyName;
            localStorage["history"] = JSON.stringify(oldHistoryData);
            render_history();

            _gaq.push(['_trackEvent', 'option_save_as', 'clicked']);
        }

        function delete_history(){
            var historyNode = document.getElementById("my_history");
            var index = historyNode.selectedIndex;
            var historyName = historyNode.options[index].value;
            if(localStorage['history'] === undefined || localStorage['history'] === "{}"){
                alert("There is nothing to be deleted!  Following is the default value.");
                return false;
            }
            if(!confirm("Are you sure to delete config data named "+historyName + "?")){
                return false;
            }
            var oldHistoryData = JSON.parse(localStorage["history"]);
            delete oldHistoryData[historyName];
            historyNode.removeChild(historyNode.options[index]);
            if(historyNode.options.length > 0){
                localStorage["config_name"] = historyNode.options[0].value;
            }else{
                delete localStorage['config_name'];
            }
            localStorage["history"] = JSON.stringify(oldHistoryData);

            render_history();
            restore_options();

        }

        function change_swap_type(){
            var typeNodes = document.getElementsByName("swap_type");
            for(var i=0;i<typeNodes.length;i++){
                typeNodes[i].onclick = function(){
                    restore_swap_style(this.value);
                }
            }
        }

        function change_config(){
            var historyNode = document.getElementById("my_history");
            historyNode.onchange = function(){
                var appData = JSON.parse(localStorage['history'])[this.value];
                for (var x in nodeDefault) {
                    var nodeId = x;
                    document.getElementById(nodeId).value = appData[x];
                }
                localStorage["config_name"] = this.value;

                restore_swap_style(appData['swap_type'], appData['gip_app_id'], appData['frame_url']);

                show_tip("<span>Config has been switched to "+this.value+"</span>");
            }
        }

        function reset_options() {
            for (var x in nodeDefault) {
                document.getElementById(x).value = nodeDefault[x];
            }
            _gaq.push(['_trackEvent', 'option_reset', 'clicked']);
        }

        function show_tip(txt){
            var status = document.getElementById("save_status");
            status.innerHTML = "<span>"+txt+"</span>";
            setTimeout(function(){
                status.innerHTML = "";
            }, 2000);
        }

        // Restores state to saved value from localStorage.
        function restore_options() {
            var historyName = localStorage["config_name"] || "Default";
            var appData = (localStorage['history'] && JSON.parse(localStorage["history"])[historyName]) || nodeDefault;
            for (var x in nodeDefault) {
                var nodeVal = appData[x];
                if(typeof(nodeVal) == "undefined"){
                    nodeVal = appData[x];
                }
                document.getElementById(x).value = nodeVal;
            }

            restore_swap_style(appData['swap_type'], appData['gip_app_id'], appData['frame_url']);

        }

        function restore_swap_style(swapType, appId, frame_url){
            swapType = swapType || "1";
            document.getElementsByName("swap_type")[parseInt(swapType)-1].checked = true;
            var wrapperId = "swap_type_wrapper_"+swapType;
            if(SWAP_TYPE_WRAPPER_ID){
                document.getElementById("swap_type_wrapper_"+SWAP_TYPE_WRAPPER_ID).style.display = "none";
            }
            document.getElementById(wrapperId).style.display = "block";

            SWAP_TYPE_WRAPPER_ID = swapType;
            if(appId){
                document.getElementById("gip_app_id").value = appId;
            }
			if(frame_url){
				document.getElementById("frame_url").value = frame_url;
			}

        }
        function format_config(node){
            //node.value = js_beautify(node.value, {"indent_size":1, "indent_char":"\t"}); 
        }

        function render_history(){
            var data = {"Default" : nodeDefault};
            if(localStorage['history']!==undefined && localStorage['history']!=="{}"){
                data = JSON.parse(localStorage['history'] || "{}");
            }
            var node = document.getElementById("my_history");
            var historyName = localStorage["config_name"];
            if(data === undefined || node === undefined){
                return false;
            }

            node.options.length = 0;
            for(var x in data){
                var option = new Option(x,x);
                node.appendChild(option);
                if(x == historyName){
                    option.selected = true;
                }
            }
        }